/*
 * Copyright (c) 2006 Zsolt Szasz <zsolt at lorecraft dot com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.lorecraft.rssappender;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.helpers.LogLog;

class BareHttpdConnection extends Thread {
	private Socket sock;
	private final BareHttpd httpd;

	BareHttpdConnection(Socket s, BareHttpd httpd) {
		sock = s;
		this.httpd = httpd;
		setPriority(NORM_PRIORITY - 1);
		start();
	}

	public void run() {
		try {
			OutputStream out = sock.getOutputStream();

			BufferedReader d = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			String req = d.readLine();
			
			// The request from a browser should be in the form: "GET /path/file.xyz"
			StringTokenizer st = new StringTokenizer(req);

			if ((st.countTokens() >= 2) && st.nextToken().equals("GET")) {
				req = st.nextToken();
			} else {
				new PrintStream(out).println("400 Bad Request");
				return;
			} 
			
			Map headers = new HashMap();
			String headerLine;
			// read the headers
			while ((headerLine = d.readLine()) != null && headerLine.length() > 0) {
				int separatorIndex = headerLine.indexOf(':');
				if (separatorIndex > 0 && separatorIndex < (headerLine.length() - 1)) {
					headers.put(headerLine.substring(0, separatorIndex).trim().toLowerCase(), headerLine.substring(separatorIndex + 1).trim());
				}
			}
			httpd.getHandler(req).handle(headers, out);				
			sock.close();
		} catch (IOException e) {
			LogLog.error("I/O error " + e);
		}
	}
}